<template>
  <a-spin :spinning="confirmLoading" style="margin-bottom: 20px;">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" slot="detail" destroyOnClose labelAlign="left">
        <a-row v-if="showInfo">
          <a-col :span="24">
            <a-form-model-item label="公司/机构名称" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-input v-model="model.name" placeholder="请输入"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="统一社会信用代码" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-input v-model="model.unifiedSocialCreditIdentifier" placeholder="请输入18位社会信用代码"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="法定代表人" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-input v-model="model.legalRepresentative" placeholder="请输入"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="成立时间" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <j-date placeholder="请选择时间" v-model="model.establishedTime" :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="注册地址" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-input v-model="model.address" placeholder="请输入"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-input v-model="model.contactUser" placeholder="请输入"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-input-group compact>
                <a-select style="width: 20%" :defaultValue="model.contactNumberPrefix"
                          v-model="model.contactNumberPrefix">
                  <a-select-option value="+86">+86</a-select-option>
                  <a-select-option value="+87">+87</a-select-option>
                </a-select>
                <a-input v-model="model.contactNumber" style="width: 80%" placeholder="请输入"></a-input>
              </a-input-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="联系邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-input v-model="model.contactMail" placeholder="请输入"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="认证用户" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-select v-model="model.approveUser" placeholder="请选择用户" show-search :filter-option="filterOption">
                <a-select-option :value="item.value" v-for="(item,index) in sys_userData" :key="item.value">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="认证时间" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <j-date placeholder="请选择时间" v-model="model.approveDate" :show-time="true"
                      date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <j-dict-select-tag v-model="model.type" placeholder="请选择类型" dictCode="organization_type"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <j-dict-select-tag v-model="model.state" placeholder="请选择" dictCode="organization_state"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="允许最大层级" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-input-number :max="9" :min="0" :precision="0" :step="1" v-model="model.allowLevel"
                              placeholder="请输入允许层级" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="核算主体数量" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-input-number :min="1" :precision="0" :step="1" v-model="model.costCalculationSubject"
                              placeholder="请输入允许核算主体数量" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="组织备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea v-model="model.remark" placeholder="请输入组织备注"></a-textarea>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-if="showModule">
          <a-col :span="24">
            <a-form-model-item label="开通权限" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-form-model ref="selectModules" :model="model" :validateOnRuleChange="true"
                            :labelCol="labelCol" :wrapperCol="wrapperCol" destroyOnClose>
                <div v-for="(item, index) in model.selectModules" :key="index">
                  <a-row>
                    <a-col :span="10">
                      <a-form-model-item label="模块" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }" required>
                        <a-select v-model="item.moduleId" style="width: 100%" placeholder="选择授权模块">
                          <a-select-option v-for="moduleItem in modules" :key="moduleItem.id"
                                           :disabled="checkModule(moduleItem.id)">
                            {{ moduleItem.name }}
                          </a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="12">
                      <a-form-model-item label="有效期" :labelCol="{ span: 6 }" :wrapperCol="{ span: 18 }" required>
                        <j-date placeholder="请选择有效期" v-model="item.expire" :show-time="true"
                                date-format="YYYY-MM-DD HH:mm:ss" style="width: 50%"/>
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="2">
                      <a-button type="delete" @click="model.selectModules.splice(index, 1)"
                                style="margin-top: 4px;">删除
                      </a-button>
                    </a-col>
                  </a-row>
                </div>
                <a-button @click="model.selectModules.push({ moduleId: null, expire: '' })"
                          :disabled="formDisabled || model.selectModules.length == modules.length" type="primary" block>
                  添加模块
                </a-button>
              </a-form-model>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import {httpAction, getAction, postAction} from '@/api/manage'
import _ from 'lodash'
import JDictSelectTag from '../../../../../components/dict/JDictSelectTag.vue'

export default {
  name: 'CyPlatformOrganizationInfoForm',
  components: {
    JDictSelectTag
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      model: {
        contactNumberPrefix: '+86',
        selectModules: [],
      },
      modules: [],
      sys_userData: [], // 认证用户数据
      showInfo: true,
      showModule: true,
      labelCol: {
        xs: {span: 24},
        sm: {span: 24},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 24},
      },
      confirmLoading: false,
      url: {
        add: "/platform/cyPlatformOrganizationInfo/add",
        checkName: "/platform/cyPlatformOrganizationInfo/checkName",
        edit: "/platform/cyPlatformOrganizationInfo/edit",
        queryById: "/platform/cyPlatformOrganizationInfo/queryById",
        listModules: "/platform/cyPlatformOrganizationPermission/listModules",
      }
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
    this.listModules();

    // 认证用户
    getAction('/sys/api/getDictItems', {
      dictCode: 'sys_user,realname,id'
    }).then((res) => {
      this.sys_userData = res || []
      console.log('getDictItems sys_user =>', res)
    });
  },
  methods: {
    /**
     * 下拉框数据过滤
     */
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    add() {
      this.edit(this.modelDefault);
    },
    edit(record) {

      if (record.id) {
        this.queryById(record.id)
        if (!this.disabled && record.type) {
          switch (record.type) {
            case 'info':
              this.showModule = false
              break
            case 'module':
              this.showInfo = false
              break
          }
        }
      } else {
        this.model = Object.assign({}, record);
      }
      this.visible = true;
    },
    checkModule(id) {
      // console.log(id, this.model.selectModules)
      return !!_.find(this.model.selectModules, ['moduleId', id])
    },
    listModules() {
      getAction(this.url.listModules).then((res) => {
        this.modules = res;
      })
    },
    queryById(id) {
      getAction(this.url.queryById, {id: id}).then((res) => {
        if (res.success) {
          this.model = res.result;
        }
      })
    },
    async submitForm() {
      console.log('submitForm', this.model)
      // 校验企业信息
      if (this.showInfo) {
        if (!this.model.name) {
          this.$message.warning('请输入公司/机构名称');
          return
        }
        if (this.model.name) {
          let res = await postAction(this.url.checkName, this.model)
          if (res.success) {
            if (res.result) {
              this.$message.warning('公司/机构名称重复,请修改');
              return
            }
          }
        }
        if (!this.model.unifiedSocialCreditIdentifier) {
          this.$message.warning('请输入统一社会信用代码');
          return
        }
        if (!this.model.legalRepresentative) {
          this.$message.warning('请输入法定代表人');
          return
        }
        if (!this.model.establishedTime) {
          this.$message.warning('请选择成立时间');
          return
        }
        if (!this.model.address) {
          this.$message.warning('请选择注册地址');
          return
        }
        if (!this.model.contactUser) {
          this.$message.warning('请输入联系人');
          return
        }
        if (!this.model.contactNumber) {
          this.$message.warning('请输入联系电话');
          return
        }
        if (this.model.contactNumber && !(new RegExp(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/).test(this.model.contactNumber))) {
          this.$message.warning('请输入正确格式的手机号码');
          return
        }
        if (!this.model.contactMail) {
          this.$message.warning('请输入联系邮箱');
          return
        }
        if (this.model.contactMail && !(new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(this.model.contactMail))) {
          this.$message.warning('请输入正确格式的邮箱');
          return
        }
        if (!this.model.approveUser) {
          this.$message.warning('请选择认证用户');
          return
        }
        if (!this.model.approveDate) {
          this.$message.warning('请选择认证时间');
          return
        }
        if (!this.model.type) {
          this.$message.warning('请选择类型');
          return
        }
        if (!this.model.state) {
          this.$message.warning('请选择状态');
          return
        }
        if (!this.model.allowLevel && this.model.allowLevel !== 0 && this.model.allowLevel !== '0') {
          this.$message.warning('请输入允许最大层级');
          return
        }
        if (!this.model.costCalculationSubject) {
          this.$message.warning('请输入核算主体数量');
          return
        }
      }
      // 校验服务管理
      if (this.showModule) {
        let flag = true
        for (let i = 0; i < this.model.selectModules.length; i++) {
          let obj = this.model.selectModules[i]
          if (!obj.moduleId) {
            this.$message.warning('请选择模块');
            flag = false
            break
          }
          if (!obj.expire) {
            this.$message.warning('请选择有效期');
            flag = false
            break
          }
        }
        if (!flag) {
          return
        }
      }
      // 检验通过，提交
      this.submit()
    },
    submit() {
      const that = this;
      that.confirmLoading = true;
      let httpurl = '';
      let method = '';
      if (!this.model.id) {
        httpurl += this.url.add;
        method = 'post';
      } else {
        httpurl += this.url.edit;
        method = 'put';
      }
      httpAction(httpurl, this.model, method).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.$emit('ok');
        } else {
          that.$message.warning(res.message);
        }
      })
    }
  }
}
</script>

<style scoped></style>
